package com.dailywork.basepro.thread.concurrent.concurrent;

import com.common.constants.NumberConstants;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author sicimike
 */
public class ExchangeDemo {

    public static void main(String[] args) {

        final Exchanger<String> exchanger = new Exchanger<>();
        ExecutorService executorService = Executors.newFixedThreadPool(NumberConstants.TWO);
        executorService.submit(() -> {
            String exchangerData = "thread-1 data";
            try {
                exchangerData = exchanger.exchange(exchangerData);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Thread.currentThread().setName("thread1");
            System.out.println(Thread.currentThread().getName() + " : " + exchangerData);
        });
        executorService.submit(() -> {
            String exchangerData = "thread-2 data";
            try {
                exchangerData = exchanger.exchange(exchangerData);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Thread.currentThread().setName("thread2");
            System.out.println(Thread.currentThread().getName() + " : " + exchangerData);
        });
        ConcurrentUtils.stop(executorService);
    }
}

